<!-- 办理人事异动 -->
<template>
  <ContentCard>
    <template #header>
      <pageHeaderNew title="人事异动" :showBack="false"></pageHeaderNew>
    </template>
    <header>
      <h3 class="font-bold text-lg">温馨提示：</h3>
      <a-space direction="vertical">
        <div>
          1、请确认员工的异动生效日期等信息，系统将在生效日当天自动更新员工的在职信息。
        </div>
        <div>
          2、如需异动审批，可以选择由HR替员工发起审批，或选择由员工本人去提交审批。
        </div>
      </a-space>
    </header>
    <main class="mt-4">
      <header class="flex justify-center">
        <div class="flex flex-col justify-self-center">
          <h3 class="text-center font-bold text-[22px] mb-4">
            {{ humanInfo?.name }}
          </h3>
          <a-space size="large">
            <span>工作性质：全职</span>
            <span>员工状态：正式</span>
          </a-space>
        </div>
      </header>
      <a-form
        :model="formData.data"
        :rules="rules"
        auto-label-width
        ref="formRef"
      >
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item field="type" label="异动类型" showColon>
              <template #extra>
                <span>
                  用人单位与劳动者协商一致，方可以变更劳动合同，建议采用书面形式进行确认
                </span>
              </template>
              <a-radio-group :default-value="1" v-model="formData.data.type">
                <template v-for="item in transactionType" :key="item.id">
                  <a-radio :value="item.id">
                    <template #radio="{ checked }">
                      <a-button
                        @click="(e, id) => radioClick(e, item.id)"
                        :type="checked ? 'outline' : 'secondary'"
                        >{{ item.name }}</a-button
                      >
                    </template>
                  </a-radio>
                </template>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="reason" label="异动原因" showColon>
              <template #extra>
                <div>
                  管理异动原因,
                  <a
                    class="text-blue"
                    @click="
                      router.push({
                        name: 'HumanChangeSetting'
                      })
                    "
                    >点击这里</a
                  >
                </div>
              </template>
              <a-select v-model="formData.data.reason" style="width: 300px">
                <a-option
                  v-for="item in typeList"
                  :key="item.id"
                  :label="item.reason"
                  :value="item.id"
                ></a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="effectTime" label="生效时间" showColon>
              <a-date-picker v-model="formData.data.effectTime" />
            </a-form-item>
          </a-col>
        </a-row>
        <section>
          <header class="title">基本信息</header>
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item field="value1" label="原公司" showColon>
                <span>{{ preData.data.preCompany }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="变更为" showColon>
                <a-tree-select
                  :fieldNames="{
                    key: 'id',
                    title: 'name'
                  }"
                  :data="companyList"
                  v-model="formData.data.company"
                  placeholder="请选择"
                  dropdown-class-name="tree-drop-down-indent-size"
                >
                  <template #tree-slot-switcher-icon="node, { isLeaf }">
                    <IconDown v-if="!isLeaf" />
                    <IconStar v-if="isLeaf" />
                  </template>
                  <template #tree-slot-title="nodeData">
                    <span
                      :style="{
                        paddingLeft:
                          nodeData.level > 2
                            ? '32px'
                            : (nodeData.level - 1) * 16 + 'px'
                      }"
                    >
                      {{ nodeData.name }}
                    </span>
                  </template>
                </a-tree-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="原部门" showColon>
                <span>{{ preData.data.preDepartment }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="变更为" showColon>
                <a-tree-select
                  :fieldNames="{
                    key: 'id',
                    title: 'name'
                  }"
                  :data="deptList"
                  v-model="formData.data.department"
                  placeholder="请选择"
                  dropdown-class-name="tree-drop-down-indent-size"
                >
                  <template #tree-slot-switcher-icon="node, { isLeaf }">
                    <IconDown v-if="!isLeaf" />
                    <IconStar v-if="isLeaf" />
                  </template>
                  <template #tree-slot-title="nodeData">
                    <span
                      :style="{
                        paddingLeft:
                          nodeData.level > 2
                            ? '32px'
                            : (nodeData.level - 1) * 16 + 'px'
                      }"
                    >
                      {{ nodeData.name }}
                    </span>
                  </template>
                </a-tree-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="原职位" showColon>
                <span>{{ preData.data.prePosition }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="变更为" showColon>
                <a-tree-select
                  :fieldNames="{
                    key: 'id',
                    title: 'name'
                  }"
                  :data="positionList"
                  v-model="formData.data.position"
                  placeholder="请选择"
                  dropdown-class-name="tree-drop-down-indent-size"
                >
                  <template #tree-slot-switcher-icon="node, { isLeaf }">
                    <IconDown v-if="!isLeaf" />
                    <IconStar v-if="isLeaf" />
                  </template>
                  <template #tree-slot-title="nodeData">
                    <span
                      :style="{
                        paddingLeft:
                          nodeData.level > 2
                            ? '32px'
                            : (nodeData.level - 1) * 16 + 'px'
                      }"
                    >
                      {{ nodeData.name }}
                    </span>
                  </template>
                </a-tree-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="原职务" showColon>
                <span>{{ preData.data.preDuties }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="变更为" showColon>
                <a-select placeholder="请选择" v-model="formData.data.duties">
                  <a-option
                    v-for="item in jobList"
                    :key="item.id"
                    :value="item.id"
                    :label="item.name"
                  />
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="原职层" showColon>
                <span>{{ preData.data.preLevel }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="变更为" showColon>
                <a-select
                  placeholder="请选择"
                  v-model="formData.data.level"
                  @change="levelChange"
                >
                  <a-option
                    v-for="item in levelList"
                    :key="item.id"
                    :value="item.id"
                    :label="item.name"
                  />
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="原职级" showColon>
                <span>{{ preData.data.preLevelRange }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="变更为" showColon>
                <a-select
                  placeholder="请选择"
                  v-model="formData.data.levelRange"
                >
                  <a-option
                    v-for="item in levelRange"
                    :key="item"
                    :value="item"
                    :label="item"
                  />
                </a-select>
              </a-form-item>
            </a-col>
            <!-- <a-col :span="12">
              <a-form-item field="value1" label="原汇报上级" showColon>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="变更为" showColon>
                <a-select placeholder="请选择">
                  <a-option />
                </a-select>
              </a-form-item>
            </a-col> -->
            <a-col :span="12">
              <a-form-item field="value1" label="原工作性质" showColon>
                <span>{{ preData.data.preNatureOfWork }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="变更为" showColon>
                <a-select
                  placeholder="请选择"
                  v-model="formData.data.natureOfWork"
                >
                  <a-option
                    v-for="item in NATURE_OF_WORK"
                    :key="item.key"
                    :value="item.key"
                    :label="item.key"
                  />
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="原工作地点" showColon>
                <span>{{ preData.data.prePlace }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="变更为" showColon>
                <a-select placeholder="请选择" v-model="formData.data.place">
                  <a-option
                    v-for="item in workPlaceList"
                    :key="item.id"
                    :value="item.id"
                    :label="item.name"
                  />
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </section>
        <section v-if="formData.data.type === 1">
          <header class="title">兼任信息</header>
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item field="value1" label="原兼任公司" showColon>
                <span>{{
                  flatOrganizationList.find(
                    (item: any) => item.id == humanInfo?.companyId
                  )?.name
                }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="变更为" showColon>
                <a-tree-select
                  :fieldNames="{
                    key: 'id',
                    title: 'name'
                  }"
                  :data="companyList"
                  v-model="formData.data.concurrentCompany"
                  placeholder="请选择"
                  dropdown-class-name="tree-drop-down-indent-size"
                >
                  <template #tree-slot-switcher-icon="node, { isLeaf }">
                    <IconDown v-if="!isLeaf" />
                    <IconStar v-if="isLeaf" />
                  </template>
                  <template #tree-slot-title="nodeData">
                    <span
                      :style="{
                        paddingLeft:
                          nodeData.level > 2
                            ? '32px'
                            : (nodeData.level - 1) * 16 + 'px'
                      }"
                    >
                      {{ nodeData.name }}
                    </span>
                  </template>
                </a-tree-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="原兼任部门" showColon>
                <span>{{
                  flatOrganizationList.find(
                    (item: any) => item.id == humanInfo?.departmentId
                  )?.name
                }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="变更为" showColon>
                <a-tree-select
                  :fieldNames="{
                    key: 'id',
                    title: 'name'
                  }"
                  :data="deptList"
                  v-model="formData.data.concurrentDepartment"
                  placeholder="请选择"
                  dropdown-class-name="tree-drop-down-indent-size"
                >
                  <template #tree-slot-switcher-icon="node, { isLeaf }">
                    <IconDown v-if="!isLeaf" />
                    <IconStar v-if="isLeaf" />
                  </template>
                  <template #tree-slot-title="nodeData">
                    <span
                      :style="{
                        paddingLeft:
                          nodeData.level > 2
                            ? '32px'
                            : (nodeData.level - 1) * 16 + 'px'
                      }"
                    >
                      {{ nodeData.name }}
                    </span>
                  </template>
                </a-tree-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="原兼任职位" showColon>
                <span>{{ humanInfo?.positionName }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="变更为" showColon>
                <a-tree-select
                  :fieldNames="{
                    key: 'id',
                    title: 'name'
                  }"
                  :data="positionList"
                  v-model="formData.data.concurrentPosition"
                  placeholder="请选择"
                  dropdown-class-name="tree-drop-down-indent-size"
                >
                  <template #tree-slot-switcher-icon="node, { isLeaf }">
                    <IconDown v-if="!isLeaf" />
                    <IconStar v-if="isLeaf" />
                  </template>
                  <template #tree-slot-title="nodeData">
                    <span
                      :style="{
                        paddingLeft:
                          nodeData.level > 2
                            ? '32px'
                            : (nodeData.level - 1) * 16 + 'px'
                      }"
                    >
                      {{ nodeData.name }}
                    </span>
                  </template>
                </a-tree-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="原兼任职务" showColon>
                <span>{{
                  jobList.find((item: any) => item.id == humanInfo?.duties)
                    ?.name
                }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="变更为" showColon>
                <a-select
                  placeholder="请选择"
                  v-model="formData.data.concurrentJob"
                >
                  <a-option
                    v-for="item in jobList"
                    :key="item.id"
                    :value="item.id"
                    :label="item.name"
                  />
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="原兼任开始时间" showColon>
                <span>{{
                  jobList.find((item: any) => item.id == humanInfo?.duties)
                    ?.name
                }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="变更为" showColon>
                <a-date-picker v-model="formData.data.concurrentStartDate" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="原兼任结束时间" showColon>
                <span>{{
                  jobList.find((item: any) => item.id == humanInfo?.duties)
                    ?.name
                }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="变更为" showColon>
                <a-date-picker v-model="formData.data.concurrentEndDate" />
              </a-form-item>
            </a-col>
          </a-row>
        </section>
        <section>
          <header class="title">合同信息</header>
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item field="value1" label="原合同公司" showColon>
                <span>{{
                  contractCompany.find(
                    (item: any) => item.id == humanInfo?.duties
                  )?.name
                }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="变更为" showColon>
                <a-select
                  placeholder="请选择"
                  v-model="formData.data.contractCompany"
                >
                  <a-option
                    v-for="item in contractCompany"
                    :key="item.id"
                    :value="item.id"
                    :label="item.name"
                  />
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="原合同类型" showColon>
                <span>{{
                  contractType.find((item: any) => item.id == humanInfo?.duties)
                    ?.name
                }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="变更为" showColon>
                <a-select
                  placeholder="请选择"
                  v-model="formData.data.contractType"
                >
                  <a-option
                    v-for="item in contractType"
                    :key="item.id"
                    :value="item.id"
                    :label="item.name"
                  />
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </section>
        <section>
          <header class="title">薪酬福利</header>
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item field="value1" label="原薪酬模式" showColon>
                <span>{{
                  jobList.find((item: any) => item.id == humanInfo?.duties)
                    ?.name
                }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="变更为" showColon>
                <a-select
                  placeholder="请选择"
                  v-model="formData.data.compensationModel"
                >
                  <a-option
                    v-for="item in SALARY_MODE"
                    :key="item.value"
                    :value="item.value"
                    :label="item.value"
                  />
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="原薪酬标准" showColon>
                <span>{{ preData.data.preSalaryScale }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="变更为" showColon>
                <a-input v-model="formData.data.compensationModel"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="原社保/地址" showColon>
                <span>{{ preData.data.prePaymentPlace }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="变更为" showColon>
                <a-input v-model="formData.data.paymentPlace"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="原参保缴纳基数" showColon>
                <!-- <span>{{ preData.data.paymentPlace }}</span> -->
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="变更为" showColon>
                <a-input v-model="formData.data.compensationModel"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="公积金缴纳比例" showColon>
                <span>{{ preData.data.preFundRatio }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="变更为" showColon>
                <a-input v-model="formData.data.fundRatio"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="公积金缴纳基数" showColon>
                <span>{{ preData.data.preReserveFundBase }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="变更为" showColon>
                <a-input v-model="formData.data.reserveFundBase"></a-input>
              </a-form-item>
            </a-col>
          </a-row>
        </section>
        <section>
          <header class="title">考勤信息</header>
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item field="value1" label="原考勤组" showColon>
                <span>{{
                  jobList.find((item: any) => item.id == humanInfo?.duties)
                    ?.name
                }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="变更为" showColon>
                <a-select
                  placeholder="请选择"
                  v-model="formData.data.compensationModel"
                >
                  <a-option
                    v-for="item in attendanceSectionList"
                    :key="item.id"
                    :value="item.id"
                  >
                    {{
                      item.type === 1
                        ? '自然月'
                        : `${month[item.startMouth]}${item.startDay}日至${
                            month[item.endMouth]
                          }${item.endDay}日`
                    }}
                  </a-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="原工作日历" showColon>
                <span>{{
                  jobList.find((item: any) => item.id == humanInfo?.duties)
                    ?.name
                }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="变更为" showColon>
                <a-select
                  placeholder="请选择"
                  v-model="formData.data.workCalendar"
                >
                  <a-option
                    v-for="item in workCalendarList"
                    :key="item.id"
                    :value="item.id"
                    :label="item.name"
                  />
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="原考勤周期" showColon>
                <span>{{
                  jobList.find((item: any) => item.id == humanInfo?.duties)
                    ?.name
                }}</span>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="value1" label="变更为" showColon>
                <a-select
                  placeholder="请选择"
                  v-model="formData.data.attendanceCycle"
                >
                  <a-option
                    v-for="item in attendanceSectionList"
                    :key="item.id"
                    :value="item.id"
                  >
                    {{
                      item.type === 1
                        ? '自然月'
                        : `${month[item.startMouth]}${item.startDay}日至${
                            month[item.endMouth]
                          }${item.endDay}日`
                    }}
                  </a-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </section>
        <section>
          <header class="title">是否需要审批</header>
          <a-radio-group v-model="isExamine">
            <a-radio :value="true">是</a-radio>
            <a-radio :value="false">否</a-radio>
          </a-radio-group>
        </section>
      </a-form>
    </main>
    <footer>
      <a-space>
        <a-button
          class="btn"
          style="
            border: 1px rgba(242, 242, 242, 1) solid;
            background-color: #fff;
          "
          @click="$router.go(-1)"
          v-show="!isExamine"
          >取消</a-button
        >
        <a-button
          class="btn"
          type="primary"
          @click="sureTransfer"
          v-show="!isExamine"
          :loading="store.isLoading"
        >
          {{ formData.data.id ? '保存' : '发起异动' }}
        </a-button>
        <a-button class="btn" type="outline" @click="save" v-show="isExamine"
          >替员工发起审批</a-button
        >
        <a-button class="btn" type="primary" @click="save" v-show="isExamine"
          >由员工本人提交审批</a-button
        >
      </a-space>
    </footer>
  </ContentCard>
</template>

<script lang="ts" setup>
import { flatTree, dataTreeFilter, controldataTreeFilter } from '@/utils/utils';
import {
  PERSONNEL_CHANGE,
  NATURE_OF_WORK,
  SALARY_MODE
} from '@/utils/constants';
import { GetOrganizationList } from '@/apis/management/organization/organizationManagement';
import { GetPosition } from '@/apis/management/organization/positionManagement';
import { GetJobList } from '@/apis/management/organization/positionManagement';
import { GetWorkPlaceList } from '@/apis/management/organization/organizationManagement';
import { getPositionHierarchyList } from '@/apis/management/organization/baseSetting/PositionSystem/index';
import { GetHumanRosterDetail } from '@/apis/management/human/humanChange/leave';
import {
  PutTransaction,
  SendTransaction,
  GetTransactionLatestDetail
} from '@/apis/management/personnel/changeManagement/transactionManagement';
import { cloneDeep } from 'lodash';
import { Message } from '@arco-design/web-vue';
import { GetLegalEntityList } from '@/apis/management/organization/organizationManagement/LegalEntity/index';
import { GetContractGroup } from '@/apis/management/contract/baseSetting';
import { getControlValue } from '@/utils/control';
import { ChangeHumanInductionState } from '@/apis/management/personnel/changeManagement/inductionManagement';
import {
  GetAttendanceCycle,
  GetWorkCalendarList
} from '@/apis/attendance/base-setting/index';
import {
  GetHumanChangeSetting,
  GetHumanChangeSettingType
} from '@/apis/management/human/baseSetting/humanSetting';
import useGlobalParametersStore from '@/store/modules/globalParameters';
const store = useGlobalParametersStore();

const route = useRoute();
const router = useRouter();

const id = +route.query.id; // 办理人id

// const filterEnum = ['兼任', '调岗', '晋升', '降级'];
// // 异动类型
// const transactionType = PERSONNEL_CHANGE.filter((item: any) =>
//   filterEnum.includes(item.label)
// );
// const transactionType = [
//   // {
//   //   id: 1,
//   //   label: '入职'
//   // },
//   {
//     id: 2,
//     label: '转正'
//   },
//   {
//     id: 3,
//     label: '晋升'
//   },
//   {
//     id: 4,
//     label: '调岗'
//   },
//   {
//     id: 5,
//     label: '降级'
//   }
//   // {
//   //   id: 6,
//   //   label: '离职'
//   // },
//   // {
//   //   id: 7,
//   //   label: '退休'
//   // },
//   // {
//   //   id: 8,
//   //   label: '返聘'
//   // }
// ];
let formRef = ref();
const rules = {
  type: [
    {
      required: true,
      message: '请选择异动类型'
    }
  ],
  reason: [
    {
      required: true,
      message: '请选择异动原因'
    }
  ],
  effectTime: [
    {
      required: true,
      message: '请选择生效时间'
    }
  ]
};

// 更改前的信息
const formData = reactive({
  data: {
    type: 4, // 异动类型
    isDone: 2, // 是否完成 1完成 2未完成
    reason: undefined, // 异动原因
    name: '', // 异动人员姓名
    jobNum: '', // 工号
    department: undefined, // 部门
    position: undefined, // 职位
    duties: undefined, // 职务
    level: undefined, // 职层
    levelRange: '', // 职级
    natureOfWork: '', // 工作性质
    // up: undefined, // 汇报上级
    place: undefined, // 工作地点
    company: undefined, // 公司
    time: '', // 生效时间
    concurrentEndDate: '', // 兼任结束时间
    concurrentStartDate: '', // 兼任开始时间
    concurrentJob: undefined, // 兼任职务
    concurrentPosition: undefined, // 兼任职位
    concurrentDepartment: undefined, // 兼任部门
    concurrentCompany: undefined, // 兼任公司
    contractType: undefined, // 合同类型
    contractCompany: undefined, // 合同公司
    compensationModel: '', // 薪酬模式
    paymentPlace: '', // 保险缴纳地
    fundRatio: '', // 公积金缴纳比例
    reserveFundBase: '', // 公积金基数
    salaryScale: '', // 薪酬标准
    attendanceSection: '', // 考勤组
    workCalendar: '', // 工作日历
    attendanceCycle: '' // 考勤周期
  }
});

const preData = reactive({
  data: {
    preDepartment: undefined, // 部门
    prePosition: undefined, // 职位
    preDuties: undefined, // 职务
    preLevel: undefined, // 职层
    preLevelRange: '', // 职级
    preNatureOfWork: '', // 工作性质
    preUp: undefined, // 汇报上级
    prePlace: undefined, // 工作地点
    preCompany: undefined, // 公司
    preConcurrentEndDate: '', // 兼任结束时间
    preConcurrentStartDate: '', // 兼任开始时间
    preConcurrentJob: undefined, // 兼任职务
    preConcurrentPosition: undefined, // 兼任职位
    preConcurrentDepartment: undefined, // 兼任部门
    preConcurrentCompany: undefined, // 兼任公司
    preContractType: undefined, // 合同类型
    preContractCompany: undefined, // 合同公司
    preCompensationModel: '', // 薪酬模式
    prePaymentPlace: '', // 保险缴纳地
    preFundRatio: '', // 公积金缴纳比例
    preReserveFundBase: '', // 公积金基数
    preSalaryScale: '', // 薪酬标准
    preAttendanceSection: '', // 考勤组
    preWorkCalendar: '', // 工作日历
    preAttendanceCycle: '' // 考勤周期
  }
});

let typeList = ref([]);
// 获取异动类型数据
const getTypeData = async () => {
  try {
    formData.data.reason = undefined;
    const { content } = await GetHumanChangeSetting({
      pageNumber: 0,
      pageSize: -1,
      changeType: formData.data.type
    });
    typeList.value = content;
  } catch (error: unknown) {
    console.log(error);
  }
};
const radioClick = (ev: MouseEvent, id: number) => {
  formData.data.type = id;
  getTypeData();
};

let transactionType = ref([]), // 异动类型
  deptList = ref([]), // 储存部门信息，
  companyList = ref([]), // 公司信息
  flatOrganizationList = ref([]), // 储存扁平化组织信息
  positionList = ref([]), // 储存岗位信息
  flatPositionList = ref([]), // 储存扁平化组织信息
  jobList = ref([]), // 储存职务
  levelList = ref([]), // 储存职层
  levelRange = ref([]), //储存职级
  workPlaceList = ref([]), // 储存工作地点
  humanInfo = ref({}), // 人员信息
  contractCompany = ref([]), // 合同公司
  contractType = ref([]), // 合同类型
  workCalendarList = ref([]), // 工作日历
  attendanceSectionList = ref([]); // 考勤组

const month = ['上月', '本月', '次月'];

const getData = async () => {
  try {
    const [
      transactionTypeRes,
      transactionDetailRes,
      humanInfoRes,
      organizationListRes,
      positionListRes,
      jobListRes,
      levelListRes,
      workPlaceListRes,
      contractCompanyRes,
      contractTypeRes,
      attendanceSectionListRes,
      workCalendarListRes
    ] = await Promise.all([
      GetHumanChangeSettingType({
        name: '1,2'
      }),
      GetTransactionLatestDetail({
        id
      }),
      GetHumanRosterDetail({
        id
      }),
      GetOrganizationList({}),
      GetPosition({
        pageNumber: 0,
        pageSize: -1
      }),
      GetJobList({
        pageNumber: 0,
        pageSize: -1
      }),
      getPositionHierarchyList({
        pageNumber: 0,
        pageSize: -1
      }),
      GetWorkPlaceList({
        pageNumber: 0,
        pageSize: -1
      }),
      GetLegalEntityList({
        pageNumber: 0,
        pageSize: -1
      }),
      GetContractGroup({
        pageNumber: 0,
        pageSize: -1
      }),
      GetAttendanceCycle({
        pageNumber: 0,
        pageSize: -1
      }),
      GetWorkCalendarList({
        pageNumber: 0,
        pageSize: -1
      })
    ]);
    transactionType.value = transactionTypeRes;
    formData.data = transactionDetailRes;
    humanInfo.value = humanInfoRes;
    formData.data.name = humanInfo.value.name;
    formData.data.jobNum = humanInfo.value.jobNum;
    companyList.value = dealTreeData(organizationListRes, 'enable', 1, '公司');
    deptList.value = dealTreeData(organizationListRes, 'enable', 1, '部门');
    flatOrganizationList.value = flatTree(dataTreeFilter(organizationListRes));
    positionList.value = dataTreeFilter(positionListRes.content);
    flatPositionList.value = flatTree(dataTreeFilter(positionListRes.content));
    jobList.value = jobListRes.content;
    levelList.value = levelListRes.content;
    workPlaceList.value = workPlaceListRes.content;
    contractCompany.value = contractCompanyRes.content;
    contractType.value = contractTypeRes.content;
    attendanceSectionList.value = attendanceSectionListRes.content;
    workCalendarList.value = workCalendarListRes.content;
    await getPreValue();
    console.log('=======typeList=============================');
    console.log(humanInfo.value);
    console.log(formData.data);
    console.log(preData.data);
    console.log('====================================');
  } catch (error: unknown) {
    console.log(error);
  }
};
getData();

// 获取变更前的数据
const getPreValue = async () => {
  try {
    formData.data.type = formData.data.type || 1;
    formData.data.reason = formData.data.reason || undefined;
    const { changeInfoList } = await GetHumanChangeSetting({
      funcType: 1, // 人事异动写死1
      changeType: formData.data.type || 1
    });
    typeList.value = changeInfoList;
    preData.data.preCompany = flatOrganizationList.value.find(
      (item: any) => item.id == humanInfo.value?.companyId
    )?.name;
    preData.data.preDepartment = flatOrganizationList.value.find(
      (item: any) => item.id == humanInfo.value?.departmentId
    )?.name;
    preData.data.prePosition = humanInfo.value?.positionName;

    // 如果之前有修改过职位层级，则职级的数据为修改过的职层数据，否则是获取之前职层的数据
    if (formData.data.level > 0) {
      // 修改后保存的职级
      const tempLevel = levelList.value.find(
        (item: any) => item.id == formData.data.level
      );
      for (let i = tempLevel?.levelDown; i <= tempLevel?.levelUp; i++) {
        levelRange.value.push(i + '');
      }

      // 原职级
      const preLevel = levelList.value.find(
        (item: any) => item.id == humanInfo.value?.positionLevel
      );
      preData.data.preLevel = preLevel?.name;
    } else {
      const tempLevel = levelList.value.find(
        (item: any) => item.id == humanInfo.value?.positionLevel
      );
      preData.data.preLevel = tempLevel?.name;
      for (let i = tempLevel?.levelDown; i <= tempLevel?.levelUp; i++) {
        levelRange.value.push(i + '');
      }
    }
    preData.data.preDuties = jobList.value.find(
      (item: any) =>
        item.id ==
        getControlValue(
          humanInfo.value?.useTemplate?.collectionModel,
          'C1F5AA49A78EC4B4FBD487F4D5887E576'
        )
    )?.name;
    preData.data.preLevelRange = getControlValue(
      humanInfo.value?.useTemplate?.collectionModel,
      'C5B3625070EFD4698A20925CE32B31F16'
    );
    preData.data.preNatureOfWork = getControlValue(
      humanInfo.value?.useTemplate?.collectionModel,
      'C958BB875BCC8470589594CDB4C498342'
    );
    preData.data.prePlace = workPlaceList.value.find(
      (item: any) => item.id == humanInfo.value?.workPlace
    )?.name;

    preData.data.preCompensationModel = getControlValue(
      humanInfo.value?.useTemplate?.collectionModel,
      'C60E6A07E819E4922AC5F188876E6E451'
    );

    preData.data.prePaymentPlace = getControlValue(
      humanInfo.value?.useTemplate?.collectionModel,
      'CC878E7B5A1CF439983F8BDED23D5C3C4'
    );
    preData.data.preFundRatio = getControlValue(
      humanInfo.value?.useTemplate?.collectionModel,
      'C25D9A7B42901414E8B5BC53096C9A25A'
    );
    preData.data.preReserveFundBase = getControlValue(
      humanInfo.value?.useTemplate?.collectionModel,
      'C9C8CC40127B0438B9ABE70AE1A10A643'
    );
    preData.data.preSalaryScale = getControlValue(
      humanInfo.value?.useTemplate?.collectionModel,
      'C91F7D6DFA87C4DBBB006839A69F2B81F'
    );

    for (const key of Object.keys(formData.data)) {
      const preKey = `pre${key.charAt(0).toUpperCase()}${key.slice(1)}`; // 生成对应的"pre"字段名
      formData.data[key] = formData.data[key] || preData.data[preKey];
    }
    console.log('====formData================================');
    console.log(formData.data);
    console.log('====================================');
  } catch (error: unknown) {
    console.log(error);
  }
};

// 重新组合树数据(根据需要来重组树结构中的属性字段，用来新增判断是否为部门节点信息，并且改部门是否为启用状态)
const dealTreeData = (
  treeData: any,
  enable: string | undefined = 'enable',
  level = 1,
  type: '公司' | '部门' = '公司'
) => {
  const tempLevel = level;
  const data = treeData.map((item: any, index1: any) => {
    let disabled = false;
    if (item[enable] === 2 || item?.node !== type) disabled = true;
    return {
      ...item,
      ...controldataTreeFilter(item?.ctlValue),
      selectable: !disabled,
      disabled,
      level,
      children:
        item?.children && item?.children?.length
          ? dealTreeData(item?.children, enable, tempLevel + 1, type)
          : null
    };
  });
  return data;
};

// 修改职层
const levelChange = (id: number) => {
  levelRange.value = [];
  const tempLevel = levelList.value.find((item: any) => item.id == id);
  for (let i = tempLevel?.levelDown; i <= tempLevel?.levelUp; i++) {
    levelRange.value.push(i + '');
  }
  formData.data.levelRange = '';
};

let isExamine = ref(false); // 是否需要审批

// 确认调岗
const sureTransfer = async () => {
  try {
    if (await formRef.value.validate()) {
      Message.error('请填写必填的内容！');
      return;
    }
    formData.data.isDone = 2;
    const temp = cloneDeep({
      ...formData.data,
      ...preData.data
    });
    // for (let i in temp) {
    //   if (temp[i] === undefined) {
    //     temp[i] = '';
    //   } else if (i !== 'type' && i !== 'reason') temp[i] = temp[i] + '';
    // }
    if (temp.id) {
      await PutTransaction({
        ...temp
      });
      if (!store.getIsLoading) {
        router.back();
      }
    } else {
      await SendTransaction({
        ...temp,
        userId: id
      });
      await ChangeHumanInductionState({
        type: 12,
        ids: [id]
      });
    }
  } catch (error: unknown) {
    console.log(error);
  }
};
</script>

<style lang="less" scoped>
.title {
  min-height: 30px;
  font-weight: 600;
  font-size: 14px;
  background: #f5f7fb;
  padding: 5px 0;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  &::before {
    content: '';
    margin: 0 5px;
    display: inline-block;
    width: 3px;
    height: 12px;
    border-left: #409efe solid 1px;
    background: #409efe;
  }
  .title-right {
    flex: 1;
    text-align: right;
  }
}

footer {
  height: 60px;
  width: calc(100% - 100px);
  background-color: #fff;
  box-shadow: 1px -1px 10px 0 #cacaca;
  position: fixed;
  bottom: 0;
  left: 10%;
  display: flex;
  justify-content: center;
  align-items: center;

  .btn {
    min-width: 120px;
    height: 40px;
    border-radius: 5px;
  }
}
</style>
